/**
 * 连接Dy服务端的WS
 * 主要负责接收来自Dy服务端的消息
 */
const WebSocket = require("ws");
const sceneMap = require("../map/sceneMap");
const utils = require("./utils/liveInfo");
const parseWsMsg = require("./utils/wsMsg");

class DyClient {
  constructor(sceneId) {
    this.sceneId = sceneId;
    this.ws = null;
    this.msgScheduler = null;
  }
  /**
   *
   * @param {*} scheduler 消息调度器 本实例拿到的消息交给scheduler处理
   */
  async init(scheduler) {
    this.msgScheduler = scheduler;
    const { liveId } = sceneMap.getClient(this.sceneId);
    const { roomId, uniqueId, ttwid } = await utils.fetchLiveRoomInfo(liveId);
    const url = utils.getDyWsUrl(roomId, uniqueId);
    this.ws = new WebSocket(url, {
      headers: {
        "User-Agent":
          "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
        Cookie: `ttwid=${ttwid};`,
      },
    });
    this.ws.binaryType = "arraybuffer";
    this.ws.on("message", (data) => {
      if (this.ws) {
        const msgContentList = parseWsMsg(data, this.ws);
        msgContentList.forEach((msgObj) => {
          this.msgScheduler(msgObj);
        });
      }
    });
    this.ws.on("open", () => {
      console.log(`${this.sceneId}:Dy WS connected`);
    });
    this.ws.on("close", () => {
      console.log(`${this.sceneId}:Dy WS disconnected`);
     this.destroy();
     // 尝试重连
      // setTimeout(() => {
      //   console.log('尝试重连');
      //   this.init(scheduler);
      // }, 5000);
    });
    this.ws.on("error", (err) => {
      console.error(`${this.sceneId}:Dy WS error: ${err}`);
      this.destroy();
    });
    sceneMap.addClient({
      sceneId: this.sceneId,
      dyClient: this,
    });
  }

  destroy() {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
    sceneMap.removeClient(this.sceneId);
  }
}

module.exports = DyClient;
